package cn.chengpengper.seckill.goods.application.event;

import cn.chengpengper.seckill.common.constants.SeckillConstants;
import cn.chengpengper.seckill.goods.application.cache.service.SeckillGoodsCacheService;
import cn.chengpengper.seckill.goods.application.cache.service.SeckillGoodsListCacheService;
import cn.chengpengper.seckill.goods.domain.event.SeckillGoodsEvent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @author chengpeng.hu
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = SeckillConstants.EVENT_GOODS_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_EVENT_ROCKETMQ_GOODS)
public class SeckillGoodsRocketMqEventHandler implements RocketMQListener<String> {

    private final SeckillGoodsCacheService seckillGoodsCacheService;

    private final SeckillGoodsListCacheService seckillGoodsListCacheService;

    @Override
    public void onMessage(String msg) {
        log.info("SeckillGoodsRocketMqEventHandler|接收到商品事件|{}", msg);
        if (StringUtils.isBlank(msg)) {
            log.info("SeckillGoodsRocketMqEventHandler|事件参数错误");
            return;
        }
        SeckillGoodsEvent seckillGoodsEvent = this.getEventMessage(msg);
        seckillGoodsCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getId(), false);
        seckillGoodsListCacheService.tryUpdateSeckillGoodsListCacheByLock(seckillGoodsEvent.getActivityId(), false);
    }

    private SeckillGoodsEvent getEventMessage(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String eventStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillGoodsEvent.class);
    }
}
